package pls_parser;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;

import org.apache.commons.io.FileUtils;

import utils.Logger;
import analysis.UserTrace;
//import org.apache.commons.io.FileUtils;




public class UsersCSVCreator extends BufferAnalyzer {

	private HashMap<String,UserTrace> traces;
	
	private String outputdir;
	
	public UsersCSVCreator(String file, String outputdir) {
		
		this.outputdir = outputdir;
		try {
			FileUtils.deleteDirectory(new File(outputdir));
		} catch (IOException e) {
			e.printStackTrace();
		}
		new File(outputdir).mkdir();
		
		traces = new HashMap<String,UserTrace>();
		// file contains the username of the users to be processed
		try {
			BufferedReader in = new BufferedReader(new FileReader(file));
			String line;
			while((line=in.readLine())!=null) {
				String username = line.trim();
				traces.put(username,new UserTrace(username));
			}
			in.close();
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	String[] fields;
	public void analyze(String line) {
		fields = line.split("\t");
		UserTrace ut = traces.get(fields[0].trim());
		if(ut != null)
			ut.addEvent(fields[1].trim(), Long.parseLong(fields[2].trim()), fields[3].trim());
	}
	
	public void finalize() {
		for(UserTrace ut: traces.values()) 
			try {
				ut.saveToCSV(outputdir);
			} catch(Exception e) {
				e.printStackTrace();
			}
	}
	
	
	public static void main(String[] args) throws Exception {
		//UsersCSVCreator ba = new UsersCSVCreator("config/"+CityEvent.MOLE_NIGHT.toFileName(),"output/"+CityEvent.MOLE_NIGHT);
		//UsersCSVCreator ba = new UsersCSVCreator("config/"+CityEvent.GAME_SILVIO_PIOLA_11_3_2012.toFileName(),"output/"+CityEvent.GAME_SILVIO_PIOLA_11_3_2012);
		
		
		UsersCSVCreator ba = new UsersCSVCreator("config/example.txt","output/example");
		PLSParser.parse(ba);
		ba.finalize();
		Logger.logln("Done");
	}
	
}
